1. 题目描述(简单难度)

[success] 559. N 叉树的最大深度

2. 解法一:使用队列进行层序遍历,遍历过程中记录深度

import java.util.LinkedList;
class Solution {
    public int maxDepth(Node root) {
        if(root == null){
            return 0;
        }
        int res = 0;
        Deque<Node> deque = new LinkedList<>();
        deque.offer(root);
        while(!deque.isEmpty()){
            int size = deque.size();
            for(int i=0;i<size;i++){
                Node node = deque.poll();
                if(node !=null) {
                    deque.addAll(node.children);
                }
            }
            res++;
        }
        return res;
    }
}

3. 解法二:DFS

import java.util.LinkedList;
class Solution {
    public int maxDepth(Node root) {
        if (root == null) {
            return 0;
        }
        if (root.children == null) {
            return 1;
        }
        int max = 0;
        for(Node node : root.children){
           max = Math.max(max,maxDepth(node));
        }
        return max+1;
    }
}
© gaohueric all right reserved,powered by Gitbook文件修订时间: 2021-12-08 23:22:22

results matching ""

    No results matching ""